// src/store/teacher.js
import { defineStore } from 'pinia'
import apiClient from '../api'
import { teacherApi } from '../api/teacher'

export const useTeacherStore = defineStore('teacher', {
    state: () => ({
        profile: null,
        students: [],
        pendingMaterials: [],
        materials: [],
        // 添加新的状态用于报告审核模块
        guidedInternships: [],
        studentMaterials: [],
        studentEvaluationsCache: {}
    }),

    actions: {
        // 获取教师个人信息
        async getProfile() {
            try {
                const response = await teacherApi.getTeacherProfile()
                this.profile = response.data
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取教师信息失败')
            }
        },

        // 更新教师个人信息
        async updateProfile(data) {
            try {
                const response = await teacherApi.updateTeacherProfile(data)
                this.profile = response.data
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '更新教师信息失败')
            }
        },

        // 注册教师个人信息
        async registerTeacherProfile(data) {
            try {
                const response = await teacherApi.registerTeacher(data)
                this.profile = response.data
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '注册教师信息失败')
            }
        },

        async getDashboardStats() {
            try {
                // 获取指导学生数量
                const internshipsResponse = await this.getGuidedInternships()
                const studentsCount = internshipsResponse.totalElements || 0

                // 获取待审核材料数量
                const pendingMaterialsResponse = await this.getPendingMaterials()
                const pendingReports = pendingMaterialsResponse.content?.length || 0

                // 获取待评成绩数量（需要计算尚未评定成绩的学生数量）
                let pendingGrades = 0
                if (internshipsResponse.content && internshipsResponse.content.length > 0) {
                    // 获取所有学生的评定记录
                    for (const internship of internshipsResponse.content) {
                        try {
                            const evalResponse = await this.getStudentEvaluationsWithCache(internship.studentId)
                            const evaluations = evalResponse.content || evalResponse

                            // 查找该实习的评定记录
                            const internshipEvaluation = evaluations.find(evaluation => evaluation.internshipId === internship.id)
                            // 如果没有评定记录，则计入待评成绩
                            if (!internshipEvaluation) {
                                pendingGrades++
                            }
                        } catch (error) {
                            console.warn(`获取学生${internship.studentId}的评定记录失败:`, error)
                        }
                    }
                }

                return {
                    studentsCount,
                    pendingReports,
                    pendingGrades
                }
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取统计数据失败')
            }
        },

        // 获取待审核材料
        async getPendingMaterials() {
            try {
                const response = await teacherApi.getPendingMaterials()
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取待审核材料失败')
            }
        },

        // 获取指导的学生实习列表（用于学生管理模块）
        async getGuidedInternships(params) {
            try {
                const response = await teacherApi.getGuidedInternships(params)
                this.guidedInternships = response.data.content || response.data
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取指导学生实习列表失败')
            }
        },

        // 获取单个学生实习详情
        async getInternshipDetail(internshipId) {
            try {
                const response = await apiClient.get(`/internships/${internshipId}`)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取实习详情失败')
            }
        },

        // 获取学生详情
        async getStudentDetail(studentId) {
            try {
                const response = await apiClient.get(`/teacher/students/${studentId}`)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取学生详情失败')
            }
        },

        // 获取特定学生的实习材料（用于报告审核模块）
        async getStudentMaterials(studentId) {
            try {
                const response = await teacherApi.getStudentMaterials(studentId)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取学生材料失败')
            }
        },

        // 获取报告列表（使用新的待审核材料接口）
        async getReports(params) {
            try {
                // 如果是获取待审核报告，则使用新的待审核材料接口
                if (params && params.status === 0) {
                    const response = await teacherApi.getPendingMaterials({ params })
                    return response.data
                } else {
                    // 其他情况可以使用原有接口或根据需要调整
                    const response = await apiClient.get('/teacher/reports', { params })
                    return response.data
                }
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取报告列表失败')
            }
        },

        // 获取材料详情
        async getMaterialDetail(materialId) {
            try {
                const response = await apiClient.get(`/internship-materials/${materialId}`)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取材料详情失败')
            }
        },

        // 审核材料
        async reviewMaterial(materialId, data) {
            try {
                const reviewData = {
                    materialId: materialId,
                    status: data.status,
                    ...(data.rejectReason && { rejectReason: data.rejectReason }),
                    ...(data.comment && { comment: data.comment })
                };

                const response = await teacherApi.reviewMaterial(reviewData)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '审核材料失败')
            }
        },

        // 更新实习状态
        async updateInternshipStatus(internshipId, status) {
            try {
                // 将 status 作为查询参数传递
                const response = await apiClient.put(`/internships/${internshipId}/status?status=${status}`)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '更新实习状态失败')
            }
        },

        // 获取成绩列表
        async getGrades(params) {
            try {
                const response = await apiClient.get('/teacher/grades', { params })
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取成绩列表失败')
            }
        },
        // 获取待评定实习成绩列表
        async getPendingEvaluations(params) {
            try {
                const response = await teacherApi.getPendingEvaluations(params)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取待评定列表失败')
            }
        },

        // 获取学生评定记录（带缓存）
        async getStudentEvaluationsWithCache(studentId) {
            // 确保 studentEvaluationsCache 已初始化
            if (!this.studentEvaluationsCache) {
                this.studentEvaluationsCache = {};
            }

            // 如果缓存中已有数据，直接返回
            if (this.studentEvaluationsCache[studentId]) {
                return this.studentEvaluationsCache[studentId];
            }

            try {
                const response = await teacherApi.getStudentEvaluations(studentId);
                // 缓存结果
                this.studentEvaluationsCache[studentId] = response.data;
                return response.data;
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取学生评定记录失败');
            }
        },

        // 清除评定记录缓存（用于刷新数据）
        clearStudentEvaluationsCache() {
            this.studentEvaluationsCache = {};
        },


        // 提交学生实习成绩评定
        async evaluateInternship(evaluationData) {
            try {
                const response = await teacherApi.evaluateInternship(evaluationData)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '成绩评定失败')
            }
        },

        // 获取成绩详情
        async getGradeDetail(gradeId) {
            try {
                const response = await apiClient.get(`/teacher/grades/${gradeId}`)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取成绩详情失败')
            }
        },

        // 提交成绩
        async submitGrade(gradeId, data) {
            try {
                const response = await apiClient.put(`/teacher/grades/${gradeId}`, data)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '提交成绩失败')
            }
        },

        // 更新成绩
        async updateGrade(gradeId, data) {
            try {
                const response = await apiClient.put(`/teacher/grades/${gradeId}/update`, data)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '更新成绩失败')
            }
        }
    }
})
